#include "queuemanager.h"
#include "ui_queuemanager.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <QDebug>
#include <QTcpSocket>

QueueManager::QueueManager(QString addr, uint port, QWidget *parent) :
		QMainWindow(parent),
		ui(new Ui::QueueManager)
{
    ui->setupUi(this);
	t = new QTimer(this);
	t->setInterval(100);
	connect(t, SIGNAL(timeout()), this, SLOT(updateGui()));
	t->start();
	_addr = addr;
	_port = port;
	ui->lable_con->setText("Connecting to " + _addr + " on port " + QString::number(_port, 10));
}

QueueManager::~QueueManager()
{
    delete ui;
}

void QueueManager::updateGui()
{
	int sockfd, portno, n;
	struct sockaddr_in serv_addr;
	struct hostent *server;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
	{
		ui->lable_con->setText("Could not create socket");
		return;
	}
	server = gethostbyname(_addr.toStdString().c_str());
	if (server == NULL) {
		ui->lable_con->setText("No such host " + _addr);
		return;
	}
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	bcopy((char *)server->h_addr,
		  (char *)&serv_addr.sin_addr.s_addr,
		  server->h_length);
	serv_addr.sin_port = htons(_port);
	if (::connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
	{
		ui->lable_con->setText("Could not connect to " + _addr + " on port " + QString::number(_port, 10));
		return;
	}
	n = read(sockfd,buffer,255);
	if (n < 0)
	{
		ui->lable_con->setText("Error readding from socket");
	}
	QString data(buffer);
	QStringList lines = data.split("\n", QString::SkipEmptyParts);
	uint l = lines.at(0).toInt();
	if(l == 0)
	{
		ui->lable_con->setText("No queues on " + _addr);
		return;
	}
	ui->lable_con->setText("Connected to " + _addr + " on port " + QString::number(_port, 10));
	for(int i = 1; i< lines.size(); i++)
	{
		QStringList names = lines.at(i).split(":", QString::SkipEmptyParts);
		if(names.size() != 2)
			continue;
		QString name = names.at(0);
		QStringList numbers = names.at(1).split("/", QString::SkipEmptyParts);
		uint val = numbers.at(0).toInt();
		uint max = numbers.at(1).toInt();
		if(!queues.contains(name))
		{
			QProgressBar *b = new QProgressBar(this);
			b->setFormat( name + ": %v/%m");;
			b->setMaximum(max);
			b->setMinimum(0);
            b->setValue(val);
			ui->verticalLayout->addWidget(b);
			b->show();
			queues.insert(name, b);
		}
		else
		{
			QProgressBar *b = queues.value(name, NULL);
            b->setValue(val);
		}
	}
}

void QueueManager::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
